<template>
    <u-col class="white">
        <!--    假如按时间排序，范围不限2-10公里内，查询添加了匹配的用户，创建匹配的时候需要选择图片，图片会默认选择个人相册中的，-->
        <v-app-bar color="white" app
                   hide-on-scroll
        >
            <v-app-bar-nav-icon @click.stop="drawer = !drawer"></v-app-bar-nav-icon>

            <v-spacer></v-spacer>
            <v-btn v-if="showInstallApp" depressed color="error" class="font-normal" @click="toInstallAPP">
                安装APP
                <v-icon right class="font24">add_box</v-icon>
            </v-btn>

            <v-spacer></v-spacer>
            <template v-if="!loginUser">
                <v-btn small text color="primary" class="font-normal pr-0" @click="toLoginVue">
                    <v-icon left class="font26">account_box</v-icon>
                    登录
                </v-btn>
            </template>
            <v-btn v-else text color="secondary" class="font-normal pl-0" @click="toQingchiIssuesReadme">
                客服/举报
                <v-icon right class="font24">error_outline</v-icon>
            </v-btn>

            <template v-if="loginUser" v-slot:extension>
                <v-tabs
                        background-color="transparent"
                        v-model="homeType"
                        @change="initMatchUsers()"
                >
                    <v-tab :href="'#'+$const.homeType.all">全国</v-tab>
                    <v-tab :href="'#'+$const.homeType.likeMe">喜欢我的</v-tab>
                    <v-tab :href="'#'+$const.homeType.iLike">我喜欢的</v-tab>
                </v-tabs>
            </template>
        </v-app-bar>
        <v-navigation-drawer v-model="drawer" app temporary>
            <v-list>
                <v-list-item
                        v-for="item in vueList"
                        link
                        to="/report"
                >
                    <!--<v-list-item-icon>
                        <v-icon>{{ item.icon }}</v-icon>
                    </v-list-item-icon>-->
                    <v-list-item-content>
                        <v-list-item-title>{{ item }}</v-list-item-title>
                    </v-list-item-content>
                </v-list-item>
            </v-list>
        </v-navigation-drawer>
        <v-divider></v-divider>
        <v-alert class="mt-3px mb-0"
                 :value="showAdvertising"
                 dense
                 type="warning"
                 dismissible
        >
            <div class="row-between">
                注册赠送一个月会员
                <v-btn small color="primary" @click="$routerTo($routerName.login)">注册</v-btn>
            </div>
        </v-alert>
        <v-flex ref="matchbox">
            <!--            <div class="h50vh w100vw green lighten-2"></div>-->
            <v-layout v-scroll="onScroll">
                <v-flex xs6>
                    <match-item v-for="(user) in leftAry" :user="user" :key="user.id" @change="openDialog"></match-item>
                </v-flex>

                <v-flex xs6>
                    <match-item v-for="(user) in rightAry" :user="user" :key="user.id"
                                @change="openDialog"></match-item>
                </v-flex>
            </v-layout>

            <!--      悬浮刷新按钮-->
            <v-btn
                    color="accent"
                    fixed
                    small
                    bottom
                    right
                    fab
                    class="mb-50"
                    @click="initMatchUsers"

            >
                <v-icon>refresh</v-icon>
            </v-btn>
        </v-flex>
        <v-dialog
                v-model="dialogVisible" v-if="matchUser"
                width="500"
        >
            <v-card>
                <v-card-title
                        class="headline grey lighten-2"
                        primary-title
                >
                    {{matchUser.nickname}}
                </v-card-title>
                <v-carousel height="400" :show-arrows="false"
                            hide-delimiter-background
                            :cycle="false">
                    <v-carousel-item
                            v-for="img in matchUser.imgs"
                            :key="img.id"
                            :src="$imgUrl+img.img"
                    ></v-carousel-item>
                </v-carousel>
                <v-divider></v-divider>
                <v-card-actions>
                    <v-btn text color="light-blue" class="w49r" @click="closeDialog">
                        <v-icon left>arrow_back</v-icon>
                        取消
                    </v-btn>
                    <v-btn text color="pink lighten-1" class="w50r" @click="lickMatch"
                           :disabled="matchUser.likeDisabled">
                        {{matchUser.likeDisabled?'已喜欢':'喜欢'}}
                        <v-icon right>favorite</v-icon>
                    </v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </u-col>
</template>

<script lang="ts">
  import {Vue, Component, Prop, Watch} from 'vue-property-decorator'
  import {namespace} from "vuex-class"
  import User from "@/model/User"
  import Chat from "@/model/Chat"
  import message from "@/views/message/message.vue"
  import MatchAPI from "@/views/match/MatchAPI"
  import ErrorCode from "@/const/ErrorCode"
  import MatchItem from "@/views/match/MatchItem.vue"
  import HomeType from "@/const/HomeType"

  const chatModule = namespace('chat')
  const userModule = namespace('user')
  const commonModule = namespace('common')

  @Component({
    components: {
      MatchItem
    }
  })
  export default class MatchVue extends Vue {
    //只用来记录共有哪些用户，用来去重，已存在的不再查询
    matchUsers: User[] = []
    leftAry: User[] = []
    rightAry: User[] = []
    dialogVisible: boolean = false
    matchUser: User = null
    @userModule.State('user') loginUser: User
    @commonModule.State('currentDate') currentDate: Date
    // 根据照片宽度和纵横比计算照片高度
    imgWidth: number = 0
    showAdvertising: boolean = false
    deferredPrompt: any = null
    showInstallApp: boolean = true
    //下滑标识
    downScroll: boolean = false
    drawer: boolean = false

    vueList: string[] = ['举报中心']/*, '社区建设'*/

    //首页类型，tab 区分
    homeType: string = HomeType.all

    /*todo
        1级，是否在线，和上次在线时间，喜欢你的人用颜色标识，男蓝，女粉，没人每天只能喜欢5个人，调整高度显示，匹配

       支持百度搜索 title keywords等
       要支持关注，
       要支持每日喜欢次数，
       显示是否在线，上次在线时间，
       匹配页显示用户颜值，
       大图界面支持显示
       是否已认证，
       聊天友好，
       支持新增自我介绍
       */

    addHomeScreen() {
      this.deferredPrompt.prompt()
      // Wait for the user to respond to the prompt
      this.deferredPrompt.userChoice
        .then((choiceResult) => {
          if (choiceResult.outcome === 'accepted') {
            console.log('接受了安装应用')
          } else {
            console.log('拒绝了安装应用')
          }
          this.deferredPrompt = null
        })
    }

    initMatchUsers() {
      this.matchUsers = []
      this.leftAry = []
      this.rightAry = []
      this.leftHeight = 0
      this.rightHeight = 0
      this.screenHeight = 0
      this.lastScrollTop = 0
      this.loadFlag = false
      this.queryMatchUsers()
    }

    created() {
      //判断是否显示安转 APP 按钮
      if (window.matchMedia('(display-mode: standalone)').matches) {
        this.showInstallApp = false
      }

      //已经安装
      if (window.navigator.standalone === true) {
        this.showInstallApp = false
      }

      /*window.addEventListener('beforeinstallprompt', (e) => {
        // Stash the event so it can be triggered later.
        this.deferredPrompt = e
      })*/

      window.addEventListener('appinstalled', (evt) => {
        console.log('a2hs installed')
      })
      //未登录才提示注册
      if (!this.loginUser) {
        this.showAdvertising = true
      }
      this.imgWidth = Math.round(document.documentElement.clientWidth / 2 - 8)
      this.initMatchUsers()
    }

    toLoginVue() {
      /*this.$info('是否前往登陆页面', '是').then(({result}) => {
        if (result) {*/
      this.$routerTo('login')
      /* }
     })*/
    }

    leftHeight: number = 0
    rightHeight: number = 0
    screenHeight: number = 0
    loadFlag: boolean = false
    lastScrollTop: number = 0
    imgMaxHeight: number = 300

    get matchUserIds() {
      if (this.matchUsers.length) {
        return this.matchUsers.map(item => item.id)
      }
      return [0]
    }

    queryMatchUsers() {
      // 高度等内容为瀑布流相关
      MatchAPI.queryMatchUsersAPI(this.matchUserIds, this.homeType).then(res => {
        //要将后台返回的无类型转为有类型
        const users: User [] = User.getUsersBys(res.data)
        this.matchUsers.push(...users)
        users.forEach((item) => {
          //信息栏 46 + padding 8
          const padding = 52
          //如果左边高了，往右边添加，否则反之 ,用来控制瀑布流的
          const itemHeight = Math.min(this.imgWidth / item.imgs[0].aspectRatio + padding, this.imgMaxHeight + padding)
          if (this.leftHeight > this.rightHeight) {
            this.rightAry.push(item)
            this.rightHeight += itemHeight
          } else {
            this.leftAry.push(item)
            this.leftHeight += itemHeight
          }
        })
        this.screenHeight = Math.max(this.leftHeight, this.rightHeight)
        this.$nextTick(() => {
          // 没有数据了，所以一直不允许在加载，可以刷新
          // 后台分页每次30个
          if (res.data.length < 30) {
            this.loadFlag = true
          } else {
            this.loadFlag = false
          }
        })
      })
    }

    onScroll(e) {
      const dom = e.target.scrollingElement
      //记录上一次的滚动位置，判断如果是下滑
      if (this.lastScrollTop < dom.scrollTop) {
        this.downScroll = true
        //滚动条整个高度减去客户端高度，就是最大滚动高度
        const maxScrollTop = dom.scrollHeight - dom.clientHeight
        //还差1000到底就加载新的
        if (dom.scrollTop > maxScrollTop - 1000) {
          if (!this.loadFlag) {
            this.queryMatchUsers()
            this.loadFlag = true
          }
        }
      } else {
        this.downScroll = false
      }
      this.lastScrollTop = dom.scrollTop
    }

    lickMatch() {
      if (this.loginUser) {
        if (this.loginUser.imgs && this.loginUser.imgs.length) {
          if (this.loginUser.id === this.matchUser.id) {
            this.$error('不许耍赖哦，不可以自己喜欢自己')
            return
          }
          this.$info('是否确认喜欢对方', '喜欢').then(({result}) => {
            if (result) {
              this.$post('match/likeMatch', this.matchUser).then(() => {
                this.matchUser.likeDisabled = true
                this.closeDialog()
              }).catch(res => {
                if (res.status === ErrorCode.custom) {
                  this.$blbl.unUploadImg()
                }
              })
            }
          })
        } else {
          //如果有用户，就是没上传照片
          //提示未上传照片
          this.$blbl.unUploadImg()
        }
        // }
      } else {
        //提示未登录
        this.$blbl.unLoginMessage()
      }
    }

    closeDialog() {
      this.dialogVisible = false
      this.matchUser = null
    }

    openDialog(matchUser: User) {
      this.matchUser = matchUser
      this.dialogVisible = true
    }

    toInstallAPP() {
      this.$warning('是否离开，前往查看如何安装手机APP', '是').then(({result}) => {
        if (result) {
          window.open("https://gitee.com/qinkaiyuan/qingchi_issue/blob/master/README.md")
        }
      })
    }

    toQingchiIssuesReadme() {
      this.$warning('是否离开，前往联系客服或进行举报', '是').then(({result}) => {
        if (result) {
          window.open("https://gitee.com/qinkaiyuan/qingchi_issue/blob/master/README.md")
        }
      })
    }
  }
</script>
